/****************************************
 @Name：基于对象的uploadify 组件
 @Author：life 
 @Date：2014-08-15
 @Blog：http://blogs.aboutit.cn
 @Copyright：life
 @官网：v2 升级，采用自己创建dom对象来，填充预览图片
        
 */
(function($) {
	// These methods can be called by adding them as the first argument in the uploadify plugin call
	var methods = {

		init : function(options, swfUploadOptions) {
			
			/***返回对象本身****/
		    return this.each(function(i){
		    	
		    	var $this = $(this);
		    	
		    	var u_options = $.extend({
						path:'../../',
						url: "admin/uploader/up",    
						width: 100,
						height: 35,
						limit: 1,
						allow:'*',
						params:{'channel':'system_uploader'},
						display:true,
						multi:false,
						success:function(file, data, response){
							
						}
				}, options);
		    	
			    var _value_ids_array=$this.attr('value-id').split(',');
			    var objName=$this.attr('objName');
			    var remove=$this.attr('remove');
			    var all_pic_container=$this.next();
			    //如果不存在则新建一个
			    if(!all_pic_container.hasClass('pre-z')){
			    	all_pic_container=$('<div></div>').addClass('pre-z').css('display','block');
			    	$this.after(all_pic_container);
			    }
			    $this.uploadify({
			    	'buttonImage' : 'public/common/uploadify/uploader.jpg',
					'width'    : u_options.width,
					'queueID'  : 'display_file_queue',
		     	    'height'   : u_options.height,
		     		 'swf'           : 'public/common/uploadify/uploadify.swf',
		     		'uploader'      : u_options.path+u_options.url,
		     		'overrideEvents' : ['onSelectError','onDialogClose'],
		     		'removeCompleted':u_options.display,
					'fileObjName' : objName,
					'multi':u_options.multi,
					'uploadLimit' : u_options.limit,
					'queueSizeLimit' : 999,
					'fileTypeExts' : u_options.allow,
					'onUploadSuccess' : function(file, data, response) {
								var json=$.parseJSON(data);
								if(json!=null){
									if(json.code==200){
										//设置上传文件
										//给父页面赋值，同时设置预览。
										//新建外层
										//当前第一个预览图片
										var cur_index=all_pic_container.children().length+1;
										var outer_pic_wrap=$('<div></div>').attr("code",cur_index).addClass('imgbox');
										var w_upload=$('<div></div>').addClass('w_upload');
										var delete_ico=$('<a></a>').addClass('item_close').attr('title','删除').attr('href','javascript:void(0);').html('删除');
										//TODO 给删除按钮绑定事件,然后插入
										//事件绑定
										delete_ico.bind('click', function() {
											$(this).parents('.imgbox').remove();
											var limit=$this.uploadify('settings','uploadLimit');
											$this.uploadify('settings','uploadLimit',++limit);
											 //更新顺序及封面
											 uploadCoverAndSeq(all_pic_container);
										});
										
										w_upload.append(delete_ico);
										//预览图片
										var item_box=$('<div></div>').addClass('item_box').append('<img src="'+json.message+'">');
										w_upload.append(item_box);
										//添加hover事件
										w_upload.hover(
										        function () {
													    $(this).children(".fm_bg").css('display','block');
													    $(this).children(".fengmian").css('display','block');
												},function () {
													$(this).children(".fm_bg").css('display','none');
												    $(this).children(".fengmian").css('display','none');
												}
										);
										//是否是封面
										if(cur_index==1){
											w_upload.append('<div class="isfenmian" style=""></div>');
										}else{
											w_upload.append('<div class="isfenmian" style="display:none"></div>');
										}
										//顺序操作背景及按钮
										w_upload.append('<div class="fm_bg" style="display: none;"></div>');
										var fengmian_oper=$('<div></div>').addClass('fengmian').css('display','none');
										//三个按钮
										var scroll_l=$('<a></a>').addClass('scroll_l').attr('title','左移').attr('href','javascript:void(0);');
										scroll_l.click(function(){
											//左移动
											left_move(all_pic_container,$(this).parents('.imgbox'));
											
										});
										var set_fm=$('<a></a>').addClass('set_fm').attr('href','javascript:void(0);');
										set_fm.click(function(){
											setCover(all_pic_container,$(this).parents('.imgbox'));
										});
										var scroll_r=$('<a></a>').addClass('scroll_r').attr('title','右移').attr('href','javascript:void(0);');
										scroll_r.click(function(){
											//右移动
											right_move(all_pic_container,$(this).parents('.imgbox'));
											
										});
										
										fengmian_oper.append(scroll_l);fengmian_oper.append(set_fm);fengmian_oper.append(scroll_r);
										w_upload.append(fengmian_oper);
										//图片描述框
										var item_input=$('<span></span>').addClass('item_input');
										var _textarea=$('<textarea></textarea>').addClass('text_desc').addClass('c_ccc').css('resize','none').attr('cols',3).attr('rows',4).val('图片描述...');
										_textarea.click(function(event){
											event.stopPropagation();
										     if($(this).val()=='图片描述...'){$(this).val('');}
										     $('.item_input').removeClass('on');
								        	 $(this).parent().addClass('on');
										});
										var _em=$('<em></em>').addClass('hc').html('请输入图片描述');
										var _shadow=$('<i></i>').addClass('shadow').addClass('hc');
										item_input.append(_textarea);item_input.append(_em);item_input.append(_shadow);
										
										//添加进入图片容器
										outer_pic_wrap.append(w_upload);outer_pic_wrap.append(item_input);
										all_pic_container.append(outer_pic_wrap);
										/**
										for(idx in _preview_ids_array){
											$('#'+_preview_ids_array[idx]).attr('src',json.message);
										}
										for(idx in _value_ids_array){
											$('#'+_value_ids_array[idx]).val(json.message);
										}**/
										
										for(idx in _value_ids_array){
											$('#'+_value_ids_array[idx]).val(json.message);
										}
									}else{
										alert(json.message);
									}
								} 
						  //处理限额
						  var cancel=$("#"+file.id + " .cancel a");
						  if (cancel) {
							    cancel.on('click',function () {
								    //在这此处处理...
								    //通过uploadify的settings方式重置上传限制数量
							    	var limit=$this.uploadify('settings','uploadLimit');
								    $('#upload').uploadify('settings','uploadLimit', ++limit);
								    //防止手快多点几次x，把x隐藏掉
								    $(this).hide();
							    });
					       } 		
		              },
					'onUploadStart' : function(file) {//开始上传的时候增加参数
						if(all_pic_container.children().length>=u_options.limit){
							alert('只能上传'+u_options.limit+'个文件，请删除后继续上传!');return false;
						}
						if(!isEmpty(u_options.params)){
							$this.uploadify("settings", "formData", u_options.params);
						}
		             },'onCancel' : function(file) {
		            	 var limit=$this.uploadify('settings','uploadLimit');
						 $this.uploadify('settings','uploadLimit',++limit);
		             },'onSelectError' : function(file,errorCode,errorMsg) {
		                 if(errorCode==SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED){
		                	 alert("超出文件队列上传个数限制！");return false;
		                 }
		                 if(errorCode==SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT  ){
		                	 alert("超出文件上传个数限制！");return false;
		                 }
		                 if(errorCode==SWFUpload.QUEUE_ERROR.INVALID_FILETYPE ){
		                	 alert("文件类型不正确！");return false;
		                 }
		                 if(errorCode==SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE ){
		                	 alert("文件大小不可以为空！");return false;
		                 }
		             }
		     	});
		    });

		}
	}

	var default_opts = {
			path:'../../',
			url: "admin/uploader/up",    
			width: 100,
			height: 35,
			limit: 1,
			allow:'*',
			params:{'channel':'system_uploader'},
			display:true,
			multi:false,
			success:function(file, data, response){
				
			}
	};

	
	function isEmpty(obj)
	{
	    for (var name in obj) 
	    {
	        return false;
	    }
	    return true;
	};
	
	/**
	 * 更新封面及顺序
	 */
	function uploadCoverAndSeq($obj){
		$('.isfenmian').css('display','none');
		$obj.children(':first').find('.isfenmian').css('display','block');
	}
	/**
	 * 设为首页
	 */
	function setCover($container,$imgbox){
		if($imgbox.children('.w_upload').children('.isfenmian').css('display')=='block')return;
		$container.children('div :first').children('.w_upload').children(".isfenmian").css('display','none');
		$imgbox.insertBefore($container.children('div :first'));
		$imgbox.children('.w_upload').children(".isfenmian").css('display','block');
	}
	
	function left_move($container,$imgbox){
		//如果是第一个
		if($imgbox.prev().length==0)return;
		//交换
		$imgbox.insertBefore($imgbox.prev());
		uploadCoverAndSeq($container);
	}
	
	function right_move($container,$imgbox){
		//如果是最后一个
		if($imgbox.next().length==0)return;
		//交换
		$imgbox.insertAfter($imgbox.next());
		uploadCoverAndSeq($container);
	}
	
	function getJsonValue(){
		
	}
	
	$.fn.uploader = function( options ) {  
	    
	};
	
})(jQuery);

